package com.southsmart.sgeocserver.controller;

import com.southsmart.sgeocserver.exception.Asserts;
import com.southsmart.sgeocserver.service.ILayerService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 图层控制层
 * @author cjunxian
 * @date 2021/7/30
 */
@RestController
public class LayerController {

    @Resource(name = ILayerService.BEAN_NAME)
    ILayerService layerService;

    /**
     * 获取layer.json
     * @param key 数据库key
     * @return
     */
    @GetMapping(value = "{key}/layer.json")
    public String getLayerJson(@PathVariable("key")String key){
        return layerService.getLayerJson(key);
    }

    /**
     * 获取tile
     * @param key 数据库key
     * @param z z
     * @param x x
     * @param y y
     * @return
     */
    @GetMapping(value = "{key}/{z}/{x}/{y}.terrain")
    public void getTile(@PathVariable("key")String key
            , @PathVariable("z")int z, @PathVariable("x")double x, @PathVariable("y")double y, HttpServletResponse response){
        Byte[] tile = layerService.getTile(key, z, x, y);
        if(tile != null){
            try {
                response.setContentType("application/octet-stream");
                int length = tile.length;
                byte[] b = new byte[length];
                for (int i = 0; i < tile.length; i++) {
                    b[i] = tile[i];
                }
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(b, 0, length);
                outputStream.close();
            } catch (IOException e) {
                Asserts.fail(e.getMessage());
            }
        }
    }

}
